package com.lframework.jh.push.manage.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lframework.jh.push.core.annotations.security.HasPermission;
import com.lframework.jh.push.core.components.resp.InvokeResult;
import com.lframework.jh.push.core.components.resp.InvokeResultBuilder;
import com.lframework.jh.push.core.controller.DefaultBaseController;
import com.lframework.jh.push.core.exceptions.impl.DefaultClientException;
import com.lframework.jh.push.core.utils.IdUtil;
import com.lframework.jh.push.core.utils.StringUtil;
import com.lframework.jh.push.manage.bo.app.channel.AppChannelBo;
import com.lframework.jh.push.manage.bo.app.channel.AppChannelParamsBo;
import com.lframework.jh.push.service.entity.AppChannel;
import com.lframework.jh.push.service.entity.Channel;
import com.lframework.jh.push.service.service.AppChannelService;
import com.lframework.jh.push.service.service.ChannelService;
import com.lframework.jh.push.service.vo.app.channel.SetParamsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用与渠道关系
 *
 * @author zmj
 */
@Api(tags = "应用与渠道关系")
@Validated
@RestController
@RequestMapping("/app/channel")
public class AppChannelController extends DefaultBaseController {

    @Autowired
    private AppChannelService appChannelService;

    @Autowired
    private ChannelService channelService;

    @ApiOperation("查询列表")
    @HasPermission({"app:set-channel"})
    @GetMapping("/query")
    public InvokeResult<List<AppChannelBo>> query(@NotBlank(message = "应用ID不能为空！") String appId) {

        // 先把所有渠道查出来
        Wrapper<Channel> queryChannelWrapper = Wrappers.lambdaQuery(Channel.class)
                .eq(Channel::getAvailable, Boolean.TRUE).orderByAsc(Channel::getCode);
        List<Channel> channelList = channelService.list(queryChannelWrapper);

        // 再把AppChannel全查出来
        Wrapper<AppChannel> queryWrapper = Wrappers.lambdaQuery(AppChannel.class)
                .eq(AppChannel::getAppId, appId);
        List<AppChannel> appChannelList = appChannelService.list(queryWrapper);

        List<AppChannelBo> results = channelList.stream().map(t -> {
            AppChannel appChannel = appChannelList.stream().filter(item -> StringUtil.equals(item.getChannelId(), t.getId())).findFirst().orElse(null);
            AppChannelBo bo = new AppChannelBo();
            bo.setChannelId(t.getId());
            bo.setChannelName(t.getName());
            bo.setIsConfig(appChannel != null);
            bo.setAvailable(appChannel != null && appChannel.getAvailable());

            return bo;
        }).collect(Collectors.toList());

        return InvokeResultBuilder.success(results);
    }

    @ApiOperation("查询参数")
    @HasPermission({"app:set-channel"})
    @GetMapping("/params")
    public InvokeResult<AppChannelParamsBo> getParams(@NotBlank(message = "应用ID不能为空！") String appId, @NotBlank(message = "渠道ID不能为空！") String channelId) {
        Channel channel = channelService.findById(channelId);
        if (channel == null) {
            throw new DefaultClientException("渠道不存在！");
        }

        AppChannel appChannel = appChannelService.findByAppIdAndChannelId(appId, channelId);

        AppChannelParamsBo result = new AppChannelParamsBo();
        result.setTemplateParams(channel.getParams());
        result.setParams(appChannel == null ? "{}" : appChannel.getParams());
        result.setAvailable(appChannel != null && appChannel.getAvailable());

        return InvokeResultBuilder.success(result);
    }

    @ApiOperation("配置参数")
    @HasPermission({"app:set-channel"})
    @PostMapping("/params")
    public InvokeResult<Void> getParams(@Valid @RequestBody SetParamsVo vo) {
        Wrapper<AppChannel> queryWrapper = Wrappers.lambdaQuery(AppChannel.class)
                .eq(AppChannel::getAppId, vo.getAppId())
                .eq(AppChannel::getChannelId, vo.getChannelId());
        AppChannel appChannel = appChannelService.getOne(queryWrapper);
        if (appChannel == null) {
            appChannel = new AppChannel();
            appChannel.setId(IdUtil.getId());
        }
        appChannel.setAppId(vo.getAppId());
        appChannel.setChannelId(vo.getChannelId());
        appChannel.setParams(vo.getParams());
        appChannel.setAvailable(vo.getAvailable());

        appChannelService.saveOrUpdate(appChannel);
        appChannelService.cleanCacheByKey(vo.getAppId() + "_" + vo.getChannelId());

        return InvokeResultBuilder.success();
    }
}
